package com.wanghe.stack;

import java.util.Stack;

/**
 * 算法71. 简化路径
 * https://leetcode-cn.com/problems/simplify-path/
 */
public class Problem71 {

    public static void main(String[] args) {
//        String s = "/home//foo/";
//        String s = "/a/./b/../../c/";
//        String s = "/../";
//        String s = "/home/";
        String s = "/...";
        Problem71 p = new Problem71();
        System.out.println(p.simplifyPath(s));
    }

    public String simplifyPath(String path) {
        Stack<Character> characters = new Stack<>();
        Character top = null;
        for (int i = 0; i < path.length(); i++) {
            char c = path.charAt(i);
            if ('/' == c) {
                if (characters.isEmpty()) {
                    characters.push(c);
                } else {
                    top = characters.peek();
                    if ('.' == top) {
                        characters.pop();
                        characters.pop();
                        characters.push(c);
                        continue;
                    } else if ('/' == top) {
                        while ('/' == top) {
                            characters.pop();
                            if (characters.isEmpty()) {
                                break;
                            }
                            top = characters.peek();
                        }
                        characters.push(c);
                    } else {
                        characters.push(c);
                    }
                }
            } else if ('.' == c) {
                top = characters.peek();
                if ('.' == top) {
                    characters.pop();
                    if (!(1 == characters.size() && '/' == characters.peek())) {
                        // 将/符号剔除出去
                        characters.pop();
                        while (!characters.isEmpty()) {
                            top = characters.peek();
                            if (top != '/') {
                                characters.pop();
                            } else {
                                break;
                            }
                        }
                    } else {
                        continue;
                    }
                } else {
                    characters.push(c);
                }
            } else {
                characters.push(c);
            }
        }
        if (!characters.isEmpty() && '/' == characters.peek() && characters.size() > 1) {
            characters.pop();
        }
        if ('.' == characters.peek()) {
            characters.pop();
        }
        String result = "";
        for (Character c : characters) {
            result = result.concat(c.toString());
        }
        return result;
    }
}
